package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.YddUserData;
import com.itheima.mapper.YddUserDataMapper;
import com.itheima.service.YddUserDataService;
import com.itheima.untils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class YddUserDataServiceImpl extends ServiceImpl<YddUserDataMapper, YddUserData> implements YddUserDataService {
    /**
     * 点赞/取消点赞和收藏/取消收藏
     * @param type
     * @param articleId
     * @param action
     * @param request
     * @return
     */
    public void removeByType(String type, String articleId, String action, HttpServletRequest request) {
        LambdaQueryWrapper<YddUserData> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotEmpty(articleId), YddUserData::getArticleId, articleId);
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(token);
        int id = Integer.parseInt(claims.get("id").toString());
        if (action.equals("add")) {
            YddUserData userData = new YddUserData();
            userData.setArticleId(Integer.parseInt(articleId));
            userData.setUserId(id);
            userData.setType(Integer.parseInt(type));
            super.save(userData);
        } else {
            qw.eq(YddUserData::getUserId, id);
            qw.eq(YddUserData::getType, type);
            YddUserData one = super.getOne(qw);
            super.removeById(one.getId());
        }


    }
}
